package com.boc.langxiang.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.shalo.ShaloDetailContract;
import com.boc.langxiang.contract.shop.ProductCollectionContract;
import com.boc.langxiang.entity.response.CollectionContent;
import com.boc.langxiang.entity.response.ShaloBaomingContent;
import com.boc.langxiang.entity.response.ShaloDetailEntity;
import com.boc.langxiang.manager.UserInfoManager;
import com.boc.langxiang.net.H5Url;
import com.boc.langxiang.presenter.shalo.ShaloDetailPresenter;
import com.boc.langxiang.presenter.shop.ProductCollectionPresenter;
import com.boc.langxiang.ui.activity.index.ArticleDetailActivity;
import com.boc.langxiang.ui.activity.shop.OrderConfirmActivity;
import com.boc.langxiang.ui.dialog.ShaloBuyDialog;
import com.boc.langxiang.ui.dialog.ShareDialog;
import com.boc.langxiang.ui.view.webview.ObservableScrollViewCallbacks;
import com.boc.langxiang.ui.view.webview.ObservableWebView;
import com.boc.langxiang.ui.view.webview.ScrollState;
import com.boc.langxiang.util.KeyBoardUtil;
import com.boc.langxiang.util.L;
import com.boc.langxiang.util.T;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 沙龙详情
 */
public class ShaloDetailActivity extends BaseToolBarActivity implements ObservableScrollViewCallbacks,
        ShaloDetailContract.View, ProductCollectionContract.View {

    @BindView(R.id.content)
    EditText mContent;
    @BindView(R.id.webView)
    ObservableWebView mWebView;
    private int mId;
    private String webUrl;
    private ShaloDetailContract.Presenter mPresenter;
    private ShaloDetailEntity mShaloDetailEntity;
    private ProductCollectionContract.Presenter mCollectionPresenter;
    private boolean mIsCollect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shalo_detail);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        mId = intent.getIntExtra("id", -1);
        if (mId == -1) {
            finish();
            return;
        }

        initView();
        initWebViews();

        mCollectionPresenter = new ProductCollectionPresenter(this);

        mPresenter = new ShaloDetailPresenter(this);
        mPresenter.shaDetail(mId);
    }

    private void initView() {
        mContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    KeyBoardUtil.closeKeybord(ShaloDetailActivity.this);
                    boolean login = isLogin();
                    if (login) {
                        mPresenter.shaloMessage(mId, mContent.getText().toString());
                        mContent.setText("");
                        return true;
                    }
                }
                return false;
            }
        });
    }

    private void initWebViews() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String urlHead = "http://xjw.hzboc.com/langxiang/api/index.php/salon_details/" + mId+"/";
                Log.d("url", url);
                if (url.equals(webUrl)) {
                    view.loadUrl(url);
                } else if (url.startsWith(urlHead)) {
                    String key = url.replace(urlHead, "");
                    String[] split = key.split("-");
                    if (split[0].equals("collect")) {
                        mCollectionPresenter.collect(split[1]);
                        mIsCollect = true;
                    } else if (split[0].equals("buy")) {
                        showShaloBuyDialog();
                    }
                }
                return true;
            }
        });

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        mWebView.setScrollViewCallbacks(this);

        webUrl = H5Url.SALON_DETAILS + mId + "/" + UserInfoManager.getInstance().getUserInfo().getId();
        mWebView.loadUrl(webUrl);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share_black, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_share) {
            L.i("share");
            ShareDialog shareDialog = new ShareDialog();
            shareDialog.show(getSupportFragmentManager(), ArticleDetailActivity.class.getSimpleName());

            // TODO
//            mPresenter.shareClick(mId);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {

    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {

    }

    @Override
    public void showLoading() {
        if (mIsCollect) {
            mIsCollect = false;
            showProgressDialog("加入收藏...");
            return;
        }
        showProgressDialog("评论中...");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }

    @Override
    public void shaloMessageSuccess() {
        mWebView.reload();
    }

    @Override
    public void shaDetailSuccess(ShaloDetailEntity shaloDetailEntity) {
        mShaloDetailEntity = shaloDetailEntity;
    }

    @Override
    public void showAddShopCarLoading() {
        showProgressDialog("正在加入购物车...");
    }

    @Override
    public void addToShoppingCarSuccess() {
        T.showShort(mContext, "已加入购物车!");
    }

    @Override
    public void showBaomingLoading() {
        showProgressDialog("报名中...");
    }

    @Override
    public void BaomingSuccess(ShaloBaomingContent content) {
        if (content == null) {
            T.showShort(mContext, "报名失败!");
            return;
        }
        String cartid = content.getCartid();
        Intent intent = new Intent(mContext, OrderConfirmActivity.class);
        intent.putExtra("ids", cartid);
        startActivity(intent);
    }

    private void showShaloBuyDialog() {
        if (mShaloDetailEntity == null) {
            mPresenter.shaDetail(mId);
            T.showShort(mContext, "沙龙信息为空!");
            return;
        }
        ShaloBuyDialog dialog = ShaloBuyDialog.newInstance(mPresenter, mShaloDetailEntity);
        dialog.show(getSupportFragmentManager(), "ShaloBuyDialog");
    }

    /**
     * 收藏成功
     *
     * @param content
     */
    @Override
    public void onSuccess(CollectionContent content) {
        L.i(webUrl);
        mWebView.reload();
    }
}
